package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDTO;
import com.xuecheng.content.model.pojo.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author xn
* @description 针对表【course_category(课程分类)】的数据库操作Service实现
* @createDate 2023-04-24 12:12:43
*/
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory>
    implements CourseCategoryService{
    @Resource
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDTO> queryTreeNodes(String id) {
        List<CourseCategoryTreeDTO> courseCategoryTreeDTOS = courseCategoryMapper.selectTreeNodes(id);

        //将查询到的list转为map
        Map<String, CourseCategoryTreeDTO> map = courseCategoryTreeDTOS.stream()
                .collect(Collectors.toMap(CourseCategoryTreeDTO::getId, item -> item,(item,item2)->item2));

        //初始化返回数据
        List<CourseCategoryTreeDTO> courseCategoryTreeDTOList = new ArrayList<>();

        //遍历查询到的数据，将子节点放在父节点的childrenTreeNodes
        courseCategoryTreeDTOS.stream()
                .filter(item -> !item.getId().equals(id))
                .forEach(item->{
                    if (item.getParentid().equals(id)){
                        courseCategoryTreeDTOList.add(item);
                    }
                    //找到节点的父节点
                    CourseCategoryTreeDTO parent = map.get(item.getParentid());
                    if(parent!=null){
                        //父节点的子节点为空
                        if(parent.getChildrenTreeNodes()==null){
                            parent.setChildrenTreeNodes(new ArrayList<>());
                        }
                        //将节点放在父节点的childrenTreeNodes
                        parent.getChildrenTreeNodes().add(item);
                    }
                });
        System.out.println(courseCategoryTreeDTOList);
        return courseCategoryTreeDTOList;
    }
}




